/**
 * 字符串处理工具集
 */

/**
 * 将驼峰字符串转换为短横线命名
 * @param {string} str - 驼峰格式字符串
 * @returns {string} 短横线格式字符串
 * @example
 * camelToKebab('camelCaseString'); // 'camel-case-string'
 */
export const camelToKebab = (str: string): string => {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
}

/**
 * 将字符串截断到指定长度并添加后缀
 * @param {string} str - 原始字符串
 * @param {number} maxLength - 最大长度
 * @param {string} [suffix='...'] - 截断后缀
 * @returns {string} 处理后的字符串
 * @example
 * truncate('This is a long text', 10); // 'This is a...'
 */
export const truncate = (str: string, maxLength: number, suffix: string = '...'): string => {
  const availableLength = maxLength - suffix.length
  if (availableLength <= 0) return suffix.substring(0, maxLength)
  return str.length > availableLength ? str.substring(0, availableLength) + suffix : str
}

/**
 * 转义HTML特殊字符
 * @param {string} str - 原始字符串
 * @returns {string} 转义后的安全字符串
 * @example
 * escapeHTML('<div>'); // '&lt;div&gt;'
 */
export const escapeHTML = (str: string): string => {
  const escapeMap: Record<string, string> = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
  }
  return str.replace(/[&<>"']/g, m => escapeMap[m])
}

/**
 * 解析URL参数为对象
 * @param {string} url - 包含查询参数的URL字符串
 * @returns {Record<string, string | string[]>} 参数对象
 * @example
 * parseUrlParams('?name=John&age=20'); // { name: 'John', age: '20' }
 */
export const parseUrlParams = (url: string): Record<string, string | string[]> => {
  const params: Record<string, string | string[]> = {}
  new URLSearchParams(url.split('?')[1]).forEach((value, key) => {
    if (key in params) {
      const existing = params[key]
      params[key] = Array.isArray(existing) ? [...existing, value] : [existing, value]
    } else {
      params[key] = value
    }
  })
  return params
}

/**
 * 将对象序列化为URL查询字符串
 * @param {Record<string, string | number | boolean | string[]>} params - 参数对象
 * @returns {string} URL查询字符串
 * @example
 * stringifyUrlParams({ name: 'John', ids: ['1','2'] }); // 'name=John&ids=1&ids=2'
 */
export const stringifyUrlParams = (
  params: Record<string, string | number | boolean | string[]>,
): string => {
  return Object.entries(params)
    .flatMap(([key, value]) =>
      Array.isArray(value)
        ? value.map(v => `${encodeURIComponent(key)}=${encodeURIComponent(v)}`)
        : `${encodeURIComponent(key)}=${encodeURIComponent(value)}`,
    )
    .join('&')
}
